package models

type TaskDataHost struct {
	Id     int   `json:"id" xorm:"int pk autoincr"`
	TaskId int   `json:"task_id" xorm:"int not null index"`
	HostId int16 `json:"host_id" xorm:"smallint not null index"`
}

type TaskDataHostDetail struct {
	TaskDataHost `xorm:"extends"`
	Name         string `json:"name"`
	Port         int    `json:"port"`
}

func (TaskDataHostDetail) TableName() string {
	return TablePrefix + "task_data_host"
}

func datahostTableName() []string {
	return []string{TablePrefix + "d_host", "h"}
}

func (th *TaskDataHost) Remove(taskId int) error {
	_, err := Db.Where("task_id = ?", taskId).Delete(new(TaskDataHost))

	return err
}

func (th *TaskDataHost) Add(taskId int, hostIds []int) error {

	err := th.Remove(taskId)
	if err != nil {
		return err
	}

	taskDataHosts := make([]TaskDataHost, len(hostIds))
	for i, value := range hostIds {
		taskDataHosts[i].TaskId = taskId
		taskDataHosts[i].HostId = int16(value)
	}

	_, err = Db.Insert(&taskDataHosts)

	return err
}

func (th *TaskDataHost) GetHostIdsByTaskId(taskId int) ([]TaskDataHostDetail, error) {
	list := make([]TaskDataHostDetail, 0)
	fields := "th.id,th.host_id,h.name,h.port" // d_host h  dhost的字段加到这里返回
	err := Db.Alias("th").
		Join("LEFT", datahostTableName(), "th.host_id=h.id").
		Where("th.task_id = ?", taskId).
		Cols(fields).
		Find(&list)

	return list, err
}

func (th *TaskDataHost) GetTaskIdsByHostId(hostId int16) ([]interface{}, error) {
	list := make([]TaskDataHost, 0)
	err := Db.Where("host_id = ?", hostId).Cols("task_id").Find(&list)
	if err != nil {
		return nil, err
	}

	taskIds := make([]interface{}, len(list))
	for i, value := range list {
		taskIds[i] = value.TaskId
	}

	return taskIds, err
}

// 判断主机id是否有引用
func (th *TaskDataHost) HostIdExist(hostId int16) (bool, error) {
	count, err := Db.Where("host_id = ?", hostId).Count(th)

	return count > 0, err
}
